<template>
	<el-container>
		<el-header>
			<el-form :model="searchmodel" :inline="true" class="demo-form-inline" style="width: 70%; float: left;">
				<el-form-item label="姓名">
					<el-input placeholder="姓名" v-model="searchmodel.name" @input="change($event)"></el-input>
				</el-form-item>
				<el-form-item label="学号">
					<el-input placeholder="学号" v-model="searchmodel.number" @input="change($event)"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="getUsers()" icon="el-icon-search">搜索</el-button>
				</el-form-item>
			</el-form>
			<div style="float: right;">
				<el-button type="success" icon="el-icon-circle-plus" @click="addUser()"></el-button>
			</div>
		</el-header>
		<el-main style="padding: unset;">
			<el-table :max-height="tableHeight" :data="tableData" border>
				<el-table-column fixed type="expand">
					<template slot-scope="props">
						<el-container>
							<el-row>
								<el-col :lg="3" :sm="3" :xs="4" :offset="1">
									<img height="100%" width="100%" v-if="!props.row.headerPath"
										src="~@/assets/break.jpg" alt="user header" />
									<img height="100%" width="100%" v-if="props.row.headerPath"
										:src="props.row.headerPath" alt="user header" />
								</el-col>
								<el-col :lg="6" :sm="6" :xs="6" :offset="1">
									<el-form label-position="left" inline class="demo-table-expand">
										<el-form-item label="姓名:">
											<span>{{ props.row.name }}</span>
										</el-form-item>
										<el-form-item label="学号:">
											<span>{{ props.row.number }}</span>
										</el-form-item>
										<el-form-item label=" 性别:">
											<span>{{ props.row.gender }}</span>
										</el-form-item>
										<el-form-item label="班级:">
											<span>{{ props.row.classes }}</span>
										</el-form-item>
										<el-form-item label="在借读书:">
											<span>{{ props.row.books }}</span>
										</el-form-item>
									</el-form>
								</el-col>
								<el-col :lg="11" :sm="11" :xs="11" :offset="1">

								</el-col>
							</el-row>
						</el-container>
					</template>
				</el-table-column>
				<el-table-column prop="name" label="姓名">
				</el-table-column>
				<el-table-column prop="number" label="学号">
				</el-table-column>
				<el-table-column prop="gender" :formatter="formatRole" label="性别">
				</el-table-column>
				<el-table-column prop="classes" label="班级">
				</el-table-column>
				<el-table-column fixed="right" label="操作" width="100">
					<template slot-scope="scope">
						<el-button @click="handleClick(scope.row)" type="text" size="small">编辑</el-button>
						<!-- <el-button type="text" style="color: red;" @click="open2" size="small">删除</el-button> -->
					</template>
				</el-table-column>
			</el-table>
		</el-main>
		<!-- Form -->

		<el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
			<el-form :model="userModel">
				<el-row>
					<el-col :lg="12">
						<el-form-item label="学号" :label-width="formLabelWidth">
							<el-input v-if="dialogTitle === '添加用户'" v-model="userModel.number" @input="change($event)">
							</el-input>
							<label v-if="dialogTitle === '编辑用户'">{{userModel.number}}</label>
						</el-form-item>
						<el-form-item label="姓名" :label-width="formLabelWidth">
							<el-input v-model="userModel.name" @input="change($event)"></el-input>
						</el-form-item>
						<el-form-item label="班级" :label-width="formLabelWidth">
							<el-input v-model="userModel.classes" @input="change($event)"></el-input>
						</el-form-item>
						<el-form-item label="性别" :label-width="formLabelWidth">
							<el-select style="width:100%" v-model="userModel.gender" placeholder="请选择好特别">
								<el-option label="男" value="0"></el-option>
								<el-option label="女" value="1"></el-option>
							</el-select>
						</el-form-item>

					</el-col>
					<el-col :lg="12">
						<el-form-item label="头像" :label-width="formLabelWidth" style="margin-bottom: 12px;">
							<!-- <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/"
								:show-file-list="false" :on-success="handleAvatarSuccess"
								:on-preview="handlePreview"
								:before-upload="beforeAvatarUpload">
								<img v-if="userModel.headerPath" :src="userModel.headerPath" class="avatar">
								<i v-else class="el-icon-plus avatar-uploader-icon"></i>
							</el-upload> -->
							<el-upload class="avatar-uploader" action="#" :show-file-list="false"
								:before-upload="beforeAvatarUpload">
								<img v-if="userModel.headerPath" :src="userModel.headerPath" class="avatar">
								<i v-else class="el-icon-plus avatar-uploader-icon"></i>
							</el-upload>
							<el-dialog :visible.sync="dialogVisible">
								<img width="100%" :src="dialogImageUrl" alt="">
							</el-dialog>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取 消</el-button>
				<el-button v-if="dialogTitle == '添加用户'" type="primary" @click="addUserToDb()">确 定</el-button>
				<el-button v-if="dialogTitle == '编辑用户'" type="primary" @click="updateUser()">确 定</el-button>
			</div>
		</el-dialog>

	</el-container>
</template>

<script>
	// import common from './common'
	import InfiniteLoading from 'vue-infinite-loading'

	import {
		Upload
	} from 'element-ui'
	const {
		ipcRenderer
	} = window.require('electron')

	export default {
		name: 'user-page',
		components: {
			InfiniteLoading,
			Upload
		},
		data() {
			return {
				dialogImageUrl: '',
				dialogVisible: false,
				pageSize: 99999,
				currentPage: 0,
				dialogTitle: '添加用户',
				/*delete dailog*/
				delDialogVisible: false,
				/*upload*/
				imageUrl: '',
				formLabelWidth: '120px',
				userModel: {
					sequenceNumber: 1,
					id: this.$uuid.v1(),
					name: '',
					number: '',
					headerPath: '',
					gender: '0',
					classes: '',
					books: ''
				},
				searchmodel: {
					name: ''
				},
				dialogFormVisible: false,
				tableHeight: 800, //document.body.clientHeight - 120,
				tableData: [{
						name: '王小虎自传',
						number: '王小虎',
						headerPath: '',
						gender: '0',
						classes: '1',
						books: '王小虎自传1，王小虎自传2'
					},
					{
						name: '王小虎自传',
						number: '王小虎',
						headerPath: '',
						gender: '1',
						classes: '2',
						books: '王小虎自传1，王小虎自传2'
					}
				]
			}
		},
		created: function() {
			console.log(this.commonFunction.downloadImg(
				'http://img61.ddimg.cn/digital/product/15/11/1901281511_ii_cover.jpg?version=3c3bcfb7-20f0-4506-8d3b-ae6e40c6b8d3'
				))
			this.getUsers()
		},
		// // 自定义指令
		// //  vue 官方文档：https://cn.vuejs.org/v2/guide/custom-directive.html
		methods: {
			formatRole(row, column) {
				return row.state == '1' ? "女" : "男";
			},
			formatImg(row, column) {
				return;
			},
			getUsers() {
				var _self = this
				var regexp = new RegExp(_self.searchmodel.name, "i");
				var regexpNumber = new RegExp(_self.searchmodel.number, "i");
				var filter = {
					$and: [{
							name: {
								$regex: regexp
							}
						},
						{
							number: {
								$regex: regexpNumber
							}
						}
					]
				}
				this.$UserDatastore.find(filter).skip(this.currentPage * this.pageSize).limit(this.pageSize).exec(function(err, docs) {
						console.log(docs)
						//remove all user
						// for (var i = 0; i < docs.length; i++) {
						// 	_self.$UserDatastore.remove({
						// 				_id: docs[i]._id
						// 		}, {},
						// 		function() {

						// 		})
						// }
					_self.tableData = docs
				})
		},
		addUser() {
			this.dialogTitle = '添加用户'
			this.dialogFormVisible = true
			this.userModel = {
				sequenceNumber: 1,
				id: this.$uuid.v1(),
				name: '',
				number: '',
				headerPath: '',
				gender: '0',
				classes: '',
				books: ''
			}
		},
		handleClick(row) {
			console.log(row);
			this.dialogTitle = '编辑用户'
			this.userModel = row
			this.dialogFormVisible = true
		},
		change(e) {
			this.$forceUpdate()
		},
		/*upload*/
		/*async*/
		beforeAvatarUpload(file) {
			var _self = this
			const isJPG = file.type === 'image/jpeg' || 'image/gif' || 'image/png';
			const isLt2M = file.size / 1024 / 1024 < 2;

			if (!isJPG) {
				this.$message.error('上传头像图片只能是 JPG 格式!');
			}
			if (!isLt2M) {
				this.$message.error('上传头像图片大小不能超过 2MB!');
			}
			// ipcRenderer.send('pic', file.name, file.path)
			var filename = 'user/' + this.$uuid.v1();
			// var newPath = this.commonFunction.saveImg(file.path, filename)
			// _self.userModel.headerPath = filename+'.'+this.commonFunction.getImgFileExt(file.path) 
			// _self.dialogImageUrl = await this.commonFunction.preViewImg(file)
			this.userModel.headerPath = this.commonFunction.imgToBase64(file.path)
			return isJPG && isLt2M;
		},
		/*delete dialog*/
		open2() {
			this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$message({
					type: 'success',
					message: '删除成功!'
				});
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});
			});
		},
		addUserToDb() {
			var _self = this
			this.$UserDatastore.findOne({
				"number": this.userModel.number
			}, function(err, docs) {
				if (docs) {
					_self.$message({
						type: 'error',
						message: '不能添加重复用户'
					});
					return;
				}
			})
			this.$UserDatastore.insert(this.userModel, function(err, doc) {
				console.log('inserted:', doc)
				_self.dialogFormVisible = false
				_self.getUsers()
			})

			//         this.$db.find({},function(){
			//             //获取查询的数据

			//         })
			//         this.$db.update({条件},{$set:{更改的数据}},function(){

			//         })
			//         this.$db.remove({条件},{},function(){

			//         })

		},
		updateUser() {
			var _self = this
			this.$UserDatastore.update({
				_id: this.userModel._id
			}, {
				$set: this.userModel
			}, function(err, docs) {
				_self.dialogFormVisible = false
			})
		}

	},
	watch: {
			tableHeight(val) {
				console.log('sdfasdf')
				// 为了避免频繁触发resize函数导致页面卡顿，使用定时器
				if (!this.timer) {
					// 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
					this.tableHeight = val
					console.log("kkkkk" + val)
					this.timer = true
					let that = this
					setTimeout(function() {
						// 打印screenWidth变化的值
						console.log(that.tableHeight)
						that.timer = false
					}, 400)
				}
			}
		},
		mounted() {
			const that = this
			window.onresize = () => {
				return (() => {
					window.screenHeight = document.body.clientHeight
					that.tableHeight = window.screenHeight - 100
				})()
			}
		}
	}
</script>

<style scoped="scoped">
	.demo-table-expand {
		font-size: 0;
	}

	.demo-table-expand label {

		color: #99a9bf;
	}

	.demo-table-expand .el-form-item label {
		width: 100% !important;
		font-size: 20px !important;
	}

	.demo-table-expand .el-form-item {
		margin-right: 0;
		margin-bottom: 0;
		width: 50%;
	}

	.dialog-form .el-form-item {
		margin-right: 0;
		margin-bottom: 0;
		width: 50%;
	}

	/* upload */
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 170px;
		height: 170px;
		line-height: 170px;
		text-align: center;
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
	}

	.avatar {
		width: 170px;
		height: 170px;
		display: block;
	}
</style>
